﻿using System;
using System.Collections.Generic;
using System.Web;
using iTextSharp.text.pdf;
using System.Text;
using System.Data;
using System.IO;
using iTextSharp.text;
using System.Data.SqlClient;
using ebay.Dal;

/// <summary>
///OrderToPdf 的摘要说明
/// </summary>
public class ConvertToPdf
{
    /// <summary>
    /// Arial字体
    /// </summary>
    BaseFont ArialFont = BaseFont.CreateFont(
                "C:\\WINDOWS\\FONTS\\Arial.TTF", //Arial
                BaseFont.IDENTITY_H, //横向字体
                BaseFont.NOT_EMBEDDED);
    /// <summary>
    /// ArialBlack字体
    /// </summary>
    BaseFont ArialBlackFont = BaseFont.CreateFont(
                "C:\\WINDOWS\\FONTS\\ariblk.TTF", //Arial
                BaseFont.IDENTITY_H,
                BaseFont.NOT_EMBEDDED);

    /// <summary>
    /// 黑体
    /// </summary>
    BaseFont simHeiFont = BaseFont.CreateFont(
                "C:\\WINDOWS\\FONTS\\simhei.TTF", //Arial
                BaseFont.IDENTITY_H,
                BaseFont.NOT_EMBEDDED);
    /// <summary>
    /// 0 Normal 1 Blod 2 斜体
    /// </summary>
    enum FontStyle
    {
        Normal = 0,
        Bold = 1,
        Italic = 2
    }

    static float minCellHeight = 10f; //单元格最低高度

    float height_product = 2f * minCellHeight;
    float height_image = 10f * minCellHeight;
    float height_min = minCellHeight;
    float height_memo = 4f * minCellHeight;
    float height_send = 2.5f * minCellHeight;
    float height_addr = 1.4f * minCellHeight;
    float height_airmail = 4f * minCellHeight;
    float height_space = minCellHeight * 2.5f + minCellHeight * 6 * 1.4f;

    iTextSharp.text.Font font_product = null;
    iTextSharp.text.Font font_memos = null;
    iTextSharp.text.Font font_send = null;
    iTextSharp.text.Font font_send1 = null;
    iTextSharp.text.Font font_addr = null;
    iTextSharp.text.Font font_return = null;
    iTextSharp.text.Font font_Normal = null;

    float ConvertCmToBang(float Units)
    {
        return Units / 0.03527f;
    }
    public ConvertToPdf()
    {
        font_product = new iTextSharp.text.Font(ArialFont, 11, (int)FontStyle.Bold);
        font_memos = new iTextSharp.text.Font(ArialFont, 6, (int)FontStyle.Bold);
        font_send = new iTextSharp.text.Font(ArialBlackFont, 14, (int)FontStyle.Bold);
        font_send1 = new iTextSharp.text.Font(simHeiFont, 14, (int)FontStyle.Bold);
        font_addr = new iTextSharp.text.Font(ArialBlackFont, 9, (int)FontStyle.Bold);
        font_return = new iTextSharp.text.Font(ArialBlackFont, 6, (int)FontStyle.Bold);
        font_Normal = new iTextSharp.text.Font(simHeiFont, 12, (int)FontStyle.Normal);
    }

    PdfPCell CreateCell(string pText, iTextSharp.text.Font pFont, float fixHeight)
    {
        PdfPCell pcell = new PdfPCell(new Paragraph(pText, pFont));
        pcell.Border = 0;
        pcell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
        pcell.VerticalAlignment = 1;//0=Left, 1=Centre, 2=Right
        pcell.FixedHeight = fixHeight;
        return pcell;

    }

    PdfPCell CreateImgCell(string tImgName, float fixHeight, float p)
    {
        iTextSharp.text.Image pdfImg = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromFile(tImgName), BaseColor.WHITE);
        PdfPCell pcell = new PdfPCell(pdfImg, true);
        pcell.Border = 0;
        pcell.Padding = p;
        pcell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
        pcell.VerticalAlignment = 1;
        pcell.FixedHeight = fixHeight;
        if (pdfImg.Width > pcell.Width || pdfImg.Height > pcell.Height)
        {
            pdfImg.ScaleToFit(pcell.Width, pcell.Height);
        }
        pcell.Image = pdfImg;
        return pcell;
    }

    void CreatePage(ref Document doc, string[] products, string[] addrs, string webDir, string memo, string orderId, string parcel_Id, string ReturnAddresser, string DeliveryCode, string PictureId)
    {
        CreatePage1(ref doc, products, addrs, webDir, memo, orderId, parcel_Id, ReturnAddresser, DeliveryCode, PictureId);
        CreatePage2(ref doc, products);
    }
    void CreatePage1(ref Document doc, string[] products, string[] addrs, string webDir, string memo, string orderId, string parcel_Id, string ReturnAddresser, string DeliveryCode, string PictureId)
    {
        PdfPTable pdftable = new PdfPTable(3);
        pdftable.WidthPercentage = 100;
        pdftable.SetWidths(new float[] { 2f, 1f, 1f });

        for (int i = 0; i < 12; i++)
        {
            if (i % 2 == 0)
            {
                PdfPCell pcell = CreateCell(products[i / 2], font_product, height_product);
                pcell.Rowspan = 2;
                pdftable.AddCell(pcell);
            }

            if (i == 0)
            {
                PdfPCell slcell = CreateCell(DeliveryCode, font_memos, height_min); //邮寄方式缩写
                pdftable.AddCell(slcell);
                string imgPath = "";
                if (PictureId != "2")
                {
                    imgPath = webDir + "\\Images\\report\\1.jpg";
                }
                else
                {
                    imgPath = webDir + "\\Images\\report\\2.jpg";
                }
                PdfPCell imgcell = CreateImgCell(imgPath, height_image, 3f);
                imgcell.Rowspan = 10;
                pdftable.AddCell(imgcell);
            }
            if (i == 1)
            {
                PdfPCell postcell = CreateCell(orderId, font_memos, height_min); //订单号
                pdftable.AddCell(postcell);
            }
            if (i == 2)
            {
                PdfPCell postcell = CreateCell(parcel_Id, font_memos, height_min); //发货单号
                pdftable.AddCell(postcell);
            }
            if (i == 3)
            {
                PdfPCell memocell = CreateCell("Memo: " + memo, font_memos, height_memo);
                memocell.Rowspan = PictureId == "3" ? 3 : 7;
                pdftable.AddCell(memocell);

            }
            if (i == 6)
            {
                if (PictureId == "3")
                {
                    PdfPCell imgcell = CreateImgCell(webDir + "\\Images\\report\\3.jpg", height_airmail, 0);
                    imgcell.Rowspan = 4;
                    pdftable.AddCell(imgcell);
                }
            }
            if (i == 10)
            {
                PdfPCell cell = CreateCell("", font_memos, height_min);
                pdftable.AddCell(cell);
            }
            if (i == 11)
            {
                PdfPCell cell = CreateCell("", font_memos, height_min);
                pdftable.AddCell(cell);

                PdfPCell cell2 = CreateCell("", font_memos, height_min);
                pdftable.AddCell(cell2);
            }
        }
        doc.Add(pdftable);


        PdfPTable bodyTable = new PdfPTable(2);
        bodyTable.WidthPercentage = 100;
        bodyTable.SetWidths(new float[] { 1f, 1f });

        for (int i = 0; i < 7; i++)
        {
            if (i == 0)
            {
                PdfPCell sendcell = CreateCell("SEND TO : ", font_send, height_send);
                bodyTable.AddCell(sendcell);
                PdfPCell spaceCell = CreateCell("", font_addr, height_space);
                spaceCell.Rowspan = 7;
                bodyTable.AddCell(spaceCell);
                continue;
            }
            PdfPCell addrcell = CreateCell(addrs[i - 1], font_addr, height_addr);
            bodyTable.AddCell(addrcell);
        }
        doc.Add(bodyTable);
        doc.Add(new Paragraph(ReturnAddresser, font_return)); //退货地址
        doc.NewPage();
    }

    void CreatePage2(ref Document doc, string[] products)
    {
        PdfPTable pdftable = new PdfPTable(1);
        pdftable.WidthPercentage = 100;
        for (int i = 6; i < products.Length; i++)
        {
            PdfPCell pcell = CreateCell(products[i], font_product, height_product);
            pdftable.AddCell(pcell);
        }
        doc.Add(pdftable);
        doc.NewPage();
    }

    string Join(string separator, string[] val)
    {
        StringBuilder sb = new StringBuilder();
        foreach (string s in val)
        {
            if (!string.IsNullOrEmpty(s))
            {
                if (sb.Length == 0)
                {
                    sb.Append(s);
                }
                else
                {
                    sb.Append(separator).Append(s);
                }
            }
        }
        return sb.ToString();
    }


    public void Export(DataTable table_Orders, List<SqlParameter> list, ref string fileName)
    {

        int rowCount = table_Orders.Rows.Count;
        if (rowCount == 0)
            return;

        DataTable table_Cache = table_Orders.Copy();

        string old_OrderId = "";
        string new_OrderId = "";
        string[] s_product = null;
        string[] s_addr = null;

        Document pdfDocument = new Document();
        iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(0, 0, ConvertCmToBang(14.991f), ConvertCmToBang(9.982f));

        pdfDocument.SetMargins(10, 10, 2, 0);
        pdfDocument.SetPageSize(pageSize);
        string webDir = HttpContext.Current.Server.MapPath("~");
        string DownDir = webDir + "\\DownLoad";
        if (!Directory.Exists(DownDir))
        {
            Directory.CreateDirectory(DownDir);
        }
        fileName = Guid.NewGuid().ToString() + ".pdf";
        string filePath = DownDir + "\\" + fileName;

        PdfWriter.GetInstance(pdfDocument, new FileStream(filePath, FileMode.Create));
        int ip = 0;

        pdfDocument.Open();
        try
        {
            foreach (DataRow r in table_Orders.Rows)
            {
                ip++;
                new_OrderId = r["OrderId"].ToString();
                if (new_OrderId == old_OrderId)
                    continue;

                DataRow[] rows = table_Cache.Select("OrderId = '" + new_OrderId + "'", "OrderId");
                int opage = Convert.ToInt32(Math.Ceiling(rows.Length / 5m));
                s_product = new string[opage * 6];
                s_addr = new string[6];
                string parcel_Id = r["ParcelId"].ToString();
                string returnAddress = r["ReturnAddresser"].ToString();
                string addr1 = r["AddressLine1"].ToString();
                string addr2 = r["AddressLine2"].ToString();
                string addrCity = r["city"].ToString();
                string addrCounty = r["county"].ToString();
                string addrCountry = r["country"].ToString();
                string addrpostalcode = r["postalcode"].ToString();
                string city = r["city"].ToString();
                string memo = r["memo"].ToString();
                string buyerName = r["buyerName"].ToString();
                string IsReBuilderOrder = r["IsReBuilderOrder"].ToString();
                string DeliveryCode = r["DeliveryCode"].ToString();
                string PictureId = r["PictureId"].ToString();
                int rIndex = 0;

                if (!string.IsNullOrEmpty(buyerName))
                {
                    s_addr[rIndex] = buyerName;
                    rIndex++;
                }
                if (!string.IsNullOrEmpty(addr1))
                {
                    s_addr[rIndex] = addr1;
                    rIndex++;
                }
                if (!string.IsNullOrEmpty(addr2))
                {
                    s_addr[rIndex] = addr2;
                    rIndex++;
                }
                string[] cc = new string[2];
                cc[0] = city;
                cc[1] = addrCounty;
                if (!string.IsNullOrEmpty(city) || !string.IsNullOrEmpty(addrCounty))
                {
                    s_addr[rIndex] = Join(",", cc);
                    rIndex++;
                }
                cc[0] = addrpostalcode;
                cc[1] = addrCountry;
                if (!string.IsNullOrEmpty(addrpostalcode) || !string.IsNullOrEmpty(addrCountry))
                {
                    s_addr[rIndex] = Join(",", cc);
                    rIndex++;
                }
                int rowIndex = 0;
                foreach (DataRow dr in rows)
                {
                    if ((rowIndex + 1) % 6 == 0)
                    {
                        if (IsReBuilderOrder == "N")
                        {
                            s_product[rowIndex] = "AF..";
                        }
                        else
                        {
                            s_product[rowIndex] = "";
                        }
                        rowIndex++;
                        continue;
                    }
                    s_product[rowIndex] = dr["pro"].ToString();
                    rowIndex++;
                }
                if (rowIndex % 6 != 0)
                {
                    if (IsReBuilderOrder == "N")
                    {
                        s_product[rowIndex] = "AF..";
                    }
                    else
                    {
                        s_product[rowIndex] = "";
                    }
                }

                old_OrderId = new_OrderId;

                CreatePage(ref pdfDocument, s_product, s_addr, webDir, memo, new_OrderId, parcel_Id, returnAddress, DeliveryCode, PictureId);

            }
            if (pdfDocument.IsOpen())
            {
                pdfDocument.Close();
                pdfDocument.Dispose();
            }
        }
        catch (Exception ex)
        {
            fileName = "";
            Log.WriteLog(ex.ToString());

            if (pdfDocument.IsOpen())
            {
                pdfDocument.Close();
                pdfDocument.Dispose();
            }
            File.Delete(filePath);
        }
    }

    //**********************************************

    void CreateTitle(ref  PdfPTable pdftable)
    {
        PdfPCell pcell = new PdfPCell(new Paragraph("仓库", font_Normal));
        pcell.HorizontalAlignment = 1;
        pcell.FixedHeight = 22;
        pdftable.AddCell(pcell);
        pcell = new PdfPCell(new Paragraph("产品", font_Normal));
        pcell.HorizontalAlignment = 1;
        pcell.FixedHeight = 22;
        pdftable.AddCell(pcell);
        pcell = new PdfPCell(new Paragraph("仓位", font_Normal));
        pcell.HorizontalAlignment = 1;
        pcell.FixedHeight = 22;
        pdftable.AddCell(pcell);
        pcell = new PdfPCell(new Paragraph("小计", font_Normal));
        pcell.HorizontalAlignment = 1;
        pcell.FixedHeight = 22;
        pdftable.AddCell(pcell);
        pcell = new PdfPCell(new Paragraph("预出库天数", font_Normal));
        pcell.HorizontalAlignment = 1;
        pcell.FixedHeight = 22;
        pdftable.AddCell(pcell);
    }

    public void ExportProduct(DataTable table, List<SqlParameter> listparameter, ref string FileName)
    {
        if (table.Rows.Count == 0)
        {
            return;
        }

        Document pdfDocument = new Document();

        pdfDocument.SetMargins(10, 10, 2, 0);
        pdfDocument.SetPageSize(PageSize.A4);
        string webDir = HttpContext.Current.Server.MapPath("~");
        string DownDir = HttpContext.Current.Server.MapPath("~") + "\\DownLoad";
        if (!Directory.Exists(DownDir))
        {
            Directory.CreateDirectory(DownDir);
        }
        FileName = Guid.NewGuid().ToString() + ".pdf";
        string filePath = DownDir + "\\" + FileName;
        //写实例
        PdfWriter.GetInstance(pdfDocument, new FileStream(filePath, FileMode.Create));
        //打开document
        pdfDocument.Open();
        PdfPTable pdftable = new PdfPTable(5);
        pdftable.WidthPercentage = 100;
        pdftable.SetWidths(new float[] { 1f, 2f, 1f, 1f, 1f });

        PdfPCell rowSpanCell = new PdfPCell();
        PdfPCell pdfCell = new PdfPCell();
        string old_Warehouse = "NULL";
        string new_Warehouse = "NULL";
        DataRow[] rows = table.Select("", "FName,UserCode");
        try
        {
            foreach (DataRow r in rows)
            {
                new_Warehouse = Convert.ToString(r[0] == DBNull.Value ? "" : r[0]);
                if (new_Warehouse != old_Warehouse)
                {
                    List<List<ProductList>> list = GetPageListByWarehouse(new_Warehouse, table);
                    int totalQty = 0;
                    int maxRowCount = 0;
                    foreach (List<ProductList> clist in list)
                    {
                        CreateTitle(ref pdftable);
                        maxRowCount = clist.Count;
                        rowSpanCell = new PdfPCell(new Paragraph(new_Warehouse, font_Normal));
                        rowSpanCell.HorizontalAlignment = 0;
                        rowSpanCell.VerticalAlignment = 1;
                        rowSpanCell.FixedHeight = 22;
                        rowSpanCell.Rowspan = clist.Count;
                        pdftable.AddCell(rowSpanCell);
                        foreach (ProductList p in clist)
                        {
                            pdfCell = new PdfPCell(new Paragraph(p.UserCode, font_Normal));
                            pdfCell.HorizontalAlignment = 0;
                            pdfCell.VerticalAlignment = 1;
                            pdfCell.FixedHeight = 22;
                            pdftable.AddCell(pdfCell);


                            pdfCell = new PdfPCell(new Paragraph(p.FNumber, font_Normal));
                            pdfCell.HorizontalAlignment = 0;
                            pdfCell.VerticalAlignment = 1;
                            pdfCell.FixedHeight = 22;
                            pdftable.AddCell(pdfCell);


                            pdfCell = new PdfPCell(new Paragraph(p.SQty.ToString(), font_Normal));
                            pdfCell.HorizontalAlignment = 2;
                            pdfCell.VerticalAlignment = 1;
                            pdfCell.FixedHeight = 22;
                            pdftable.AddCell(pdfCell);

                            totalQty += p.SQty;

                            pdfCell = new PdfPCell(new Paragraph(p.Days.ToString("#0.0"), font_Normal));
                            pdfCell.HorizontalAlignment = 2;
                            pdfCell.VerticalAlignment = 1;
                            pdfCell.FixedHeight = 22;
                            pdftable.AddCell(pdfCell);
                        }
                    }
                    old_Warehouse = new_Warehouse;
                    PdfPCell tcell = new PdfPCell(new Paragraph(totalQty.ToString(), font_Normal));
                    tcell.HorizontalAlignment = 2;
                    tcell.VerticalAlignment = 1;
                    tcell.FixedHeight = 22;

                    pdfCell = new PdfPCell(new Paragraph("总计", font_Normal));
                    pdfCell.HorizontalAlignment = 1;
                    pdfCell.VerticalAlignment = 1;
                    pdfCell.FixedHeight = 22;

                    pdftable.AddCell(pdfCell);


                    pdfCell = new PdfPCell(new Paragraph("", font_Normal));
                    pdfCell.HorizontalAlignment = 2;
                    pdfCell.VerticalAlignment = 1;
                    pdfCell.FixedHeight = 22;
                    pdftable.AddCell(pdfCell);
                    pdftable.AddCell(pdfCell);
                    pdftable.AddCell(tcell);
                    pdftable.AddCell(pdfCell);
                    maxRowCount++;
                    if (maxRowCount == 37)
                    {
                        maxRowCount = 1;
                    }
                    while (maxRowCount < 37)
                    {
                        pdfCell = new PdfPCell(new Paragraph("", font_Normal));
                        pdfCell.Border = 0;
                        pdfCell.HorizontalAlignment = 2;
                        pdfCell.VerticalAlignment = 1;
                        pdfCell.FixedHeight = 22;
                        pdftable.AddCell(pdfCell);
                        pdftable.AddCell(pdfCell);
                        pdftable.AddCell(pdfCell);
                        pdftable.AddCell(pdfCell);
                        pdftable.AddCell(pdfCell);
                        maxRowCount++;
                    }
                }
            }
            pdfDocument.Add(pdftable);
            if (pdfDocument.IsOpen())
            {
                pdfDocument.Close();
                pdfDocument.Dispose();
            }
        }
        catch (Exception ex)
        {
            FileName = "";
            Log.WriteLog(ex.ToString());
            if (pdfDocument.IsOpen())
            {
                pdfDocument.Close();
                pdfDocument.Dispose();
            }
            File.Delete(filePath);
        }
    }
    public List<List<ProductList>> GetPageListByWarehouse(string WhouseName,DataTable dt)
    {
        DataRow[] rows = dt.Select("IsNull(FName,'') = '" + WhouseName + "'", "");
        List<List<ProductList>> list = new List<List<ProductList>>();
        List<ProductList> plist = null;
        int maxRow = 0;
        foreach (DataRow r in rows)
        {
            if (maxRow == 0)
            {
                plist = new List<ProductList>();
            }
            ProductList m = new ProductList();
            m.WarehouseName = Convert.ToString(r[0] == DBNull.Value ? "" : r[0]);
            m.UserCode = Convert.ToString(r[1] == DBNull.Value ? "" : r[1]);
            m.SQty = Convert.ToInt32(r[3] == DBNull.Value ? "0" : r[3]);
            m.FNumber = Convert.ToString(r[2] == DBNull.Value ? "" : r[2]);
            int fQty = Convert.ToInt32(r[4] == DBNull.Value ? "0" : r[4]);
            m.Days = m.SQty == 0 ? 0 : (fQty / m.SQty);
            plist.Add(m);
            maxRow++;
            if (maxRow == 37)
            {
                list.Add(plist);
                maxRow = 0;
            }
        }
        if (maxRow != 0 && maxRow != 37)
        {
            list.Add(plist);        
        }
        return list;
    }
}

public class ProductList
{
    string warehouseName;

    public string WarehouseName
    {
        get { return warehouseName; }
        set { warehouseName = value; }
    }
    string userCode;

    public string UserCode
    {
        get { return userCode; }
        set { userCode = value; }
    }
    string fNumber;

    public string FNumber
    {
        get { return fNumber; }
        set { fNumber = value; }
    }
    int sQty;

    public int SQty
    {
        get { return sQty; }
        set { sQty = value; }
    }

    double days;

    public double Days
    {
        get { return days; }
        set { days = value; }
    }
}
